import time
from multiprocessing import Process
from threading import Thread
from time import sleep


# 计算密集型
def count(x, y):
    c = 0
    while c < 7000000:
        c += 1
        x += 1
        y += 1


# IO密集函数
def io():
    write()
    read()


def write():
    f = open('test.txt', 'w')
    for i in range(1500000):
        f.write("hello world\n")
    f.close()


def read():
    f = open('test.txt')
    lines = f.readlines()
    f.close()


if __name__ == "__main__":
    # 使用单线程执行计算密集函数十次，记录时间。执行IO密集函数十次，记录时间
    print("开始执行计算密集时间:start", time.ctime())
    for i in range(10):
        count(1, 1)
    print("结束执行计算密集时间:end", time.ctime())
    print("开始执行IO密集时间:start", time.ctime())
    for i in range(10):
        io()
    print("结束执行IO密集时间:end", time.ctime())

    count_jobs = []
    io_jobs = []
    print("使用多线程执行计算密集开始时间start:", time.ctime())
    for i in range(10):
        thread = Thread(target=count, args=(1, 1))
        count_jobs.append(thread)
        thread.start()
    for job in count_jobs:
        job.join()
    print("使用多线程执行计算密集结束时间end:", time.ctime())
    print("使用多线程执行IO密集开始时间start:", time.ctime())
    for i in range(10):
        t = Thread(target=io)
        io_jobs.append(t)
        t.start()
    for job in io_jobs:
        job.join()
    print("使用多线程执行IO密集结束时间end:", time.ctime())

    # 使用10个进程分别执行计算密集函数1次和执行IO密集函数1次

    count_p_jobs = []
    io_p_jobs = []
    print("多进程执行计算密集结束时间start:", time.ctime())
    for i in range(10):
        process = Process(target=count, args=(1, 1))
        count_p_jobs.append(process)
        process.start()

    for job in count_p_jobs:
        job.join()
    print("多进程执行计算密集结束时间end:", time.ctime())

    print("多进程执行IO密集结束时间start:", time.ctime())
    for i in range(10):
        process = Process(target=io)
        io_p_jobs.append(process)
        process.start()

    for job in io_p_jobs:
        job.join()
    print("多进程执行IO密集结束时间end:", time.ctime())
